#include"stack.h"

void StackInit(Stack* ps)
{
	ps->arr = NULL;
	ps->top = 0;
	ps->capacity = 0;
}

void StackPush(Stack* ps, STDataType data)
{
	assert(ps);
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		STDataType* tmp = (STDataType*)malloc(newcapacity * sizeof(STDataType));
		if (tmp == NULL)
		{
			perror("malloc fail");
			exit(1);
		}
		ps->capacity = newcapacity;
		ps->arr = tmp;
	}
	ps->arr[ps->top++] = data;
}

void StackPop(Stack* ps)
{
	assert(ps);
	ps->top--;
}

STDataType StackTop(Stack* ps)
{
	return ps->arr[ps->top-1];
}

int StackSize(Stack* ps)
{
	return ps->top - 1;
}

int StackEmpty(Stack* ps)
{
	if (ps == NULL)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

void StackDestroy(Stack* ps)
{
	free(ps->arr);
	free(ps);
}